package com.luboyan.CBillbill.service.user.auth.impl;

import com.luboyan.CBillbill.dao.user.auth.*;
import com.luboyan.CBillbill.service.user.auth.AuthRoleService;
import com.luboyan.CBillbill.service.user.auth.UserAuthService;
import com.luboyan.CBillbill.service.user.auth.UserRoleService;
import com.luboyan.CBillbill.util.constat.UserConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户所有权限管理业务逻辑
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserRoleService userRoleService; //用于查询用户绑定了哪些角色

    @Autowired
    private AuthRoleService authRoleService; //用于查询角色绑定了哪些权限



    /**
     * 获取用户所拥有的所有权限
     */
    @Override
    public UserAuthorities getUserAuthorities(Long userId) {
        List<UserRole> userRoles = userRoleService.getUserRoleByUserId(userId);
        Set<Long> roleIdS = new HashSet<>();
        for(UserRole userRole: userRoles){
            roleIdS.add(userRole.getRoleId());
        }
        //设置了多少种权限子表就要查多少次
        List<AuthRoleElementOperation> authRoleElementOperations =
                authRoleService.getRoleElementOperationsByRoleIds(roleIdS);
        List<AuthRoleMenu> authRoleMenus =
                authRoleService.getRoleMenusByRoleIds(roleIdS);
        UserAuthorities userAuthorities = new UserAuthorities();
        userAuthorities.setRoleElementOperationList(authRoleElementOperations);
        userAuthorities.setRoleMenuList(authRoleMenus);
        return userAuthorities;
    }

    /**
     * 用户添加默认角色
     */
    @Override
    public void addUserDefaultRole(Long id) {
        UserRole userRole = new UserRole();
        AuthRole authRole = authRoleService.getRoleByCode(UserConstant.ROLE_CODE_LV0);
        userRole.setRoleId(authRole.getId());
        userRole.setId(id);
        userRole.setCreateTime(new Date());
        userRoleService.addUserRole(userRole);
    }
}
